package com.atguigu.realtime.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV2;
import com.atguigu.realtime.bean.OrderWide;
import com.atguigu.realtime.bean.PaymentInfo;
import com.atguigu.realtime.bean.PaymentWide;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.common.ConstantTopic;
import com.atguigu.realtime.util.MyKafkaUtil;
import com.atguigu.realtime.util.MyTimeUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.ProcessJoinFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;

import java.sql.SQLException;
import java.time.Duration;
import java.util.Map;

/**
 * @ClassName: DWMPaymentWideApp
 * @Description:
 * @Author: kele
 * @Date: 2021/4/23 11:44
 *
 *  支付表和订单详情表关联（ 订单详情表完成之后，需要隔一段时间才能接收都爱 ）
 *      方式一：
 *          将订单详情表作为维度表存储在Hbase中，当payment数据到达时，通过查询的方式将订单详情表的数据插入
 *      方式二：
 *          将订单详情表的数据存储在kafka中，payment的数据 用interval与订单详情数据 进行关联
 *
 *
 **/
public class DWMPaymentWideApp extends BaseAppV2 {

    public static void main(String[] args) throws SQLException, ClassNotFoundException {

        /**
         * 读取支付表和订单详情宽表
         */
        new DWMPaymentWideApp().init(30011,
                2,
                "DWMPaymentWideApp",
                "DWMPaymentWideApp",
                ConstantTopic.DWD_PAYMENT_INFO,
                ConstantTopic.DWM_ORDER_WIDE);
    }


    @Override
    protected void run(StreamExecutionEnvironment env,
                       Map<String, DataStream<String>> streams) throws SQLException, ClassNotFoundException {


        SingleOutputStreamOperator<String> paymentwide = PaymentJoinOrderWide(streams);

        send2kafka(paymentwide);
    }

    private void send2kafka(SingleOutputStreamOperator<String> paymentwide) {

        paymentwide.addSink(MyKafkaUtil.getKafkaSink("dwm_payment_wide"));

    }

    private SingleOutputStreamOperator<String> PaymentJoinOrderWide(Map<String, DataStream<String>> streams) {

        KeyedStream<PaymentInfo, Long> dwd_payment_info = streams.get("dwd_payment_info")
                .map(t -> JSON.parseObject(t, PaymentInfo.class))
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<PaymentInfo>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                                .withTimestampAssigner( (element, recordTimestamp) -> MyTimeUtil.TransfromTs(element.getCreate_time(), "yyyy-MM-dd HH:mm:ss"))
                )
                .keyBy(PaymentInfo::getOrder_id);


        KeyedStream<OrderWide, Long> dwm_order_wide = streams.get("dwm_order_wide")
                .map(t -> JSON.parseObject(t, OrderWide.class))
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<OrderWide>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                                .withTimestampAssigner((element, recordTimestamp) -> MyTimeUtil.TransfromTs(element.getCreate_time(), "yyyy-MM-dd HH:mm:ss"))
                )
                .keyBy(OrderWide::getOrder_id);

        SingleOutputStreamOperator<String> result = dwd_payment_info
                .intervalJoin(dwm_order_wide)
                .between(Time.minutes(-45), Time.minutes(0))
                .process(new ProcessJoinFunction<PaymentInfo, OrderWide, PaymentWide>() {

                    @Override
                    public void processElement(PaymentInfo payment,
                                               OrderWide order,
                                               Context ctx, Collector<PaymentWide> out) throws Exception {

                        out.collect(new PaymentWide(payment, order));


                    }
                })
                .map(JSONObject::toJSONString);

        return result;
    }
}
